package cn.initcap;

import cn.initcap.common.JsonData;
import cn.initcap.properties.SecurityConstants;
import cn.initcap.properties.SecurityProperties;
import cn.initcap.social.SocialController;
import cn.initcap.social.support.SocialUserInfo;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * @author initcap
 * @date Created in 2018/5/17 PM9:30.
 */
@Slf4j
@RestController
public class WebSecurityController extends SocialController {

    /**
     * 获取请求缓存
     */
    private RequestCache requestCache = new HttpSessionRequestCache();

    /**
     * 处理转发
     */
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    /**
     * 当需要身份认证时跳到这里
     *
     * @param request  请求
     * @param response 响应
     * @return 数据
     */
    @RequestMapping(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
    /**设置返回401状态码*/
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public JsonData requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //获取引发跳转的这个请求
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if (savedRequest != null) {
            String targetUrl = savedRequest.getRedirectUrl();
            log.info("引发跳转的请求为={}", targetUrl);
            if (StringUtils.endsWithIgnoreCase(targetUrl, ".html") || StringUtils.endsWithIgnoreCase(targetUrl, ".page")) {
                //跳转到用户配置的页面
                redirectStrategy.sendRedirect(request, response, securityProperties.getWeb().getSignInPage());
            }
        }

        return JsonData.fail("访问的服务需要身份认证，请引导用户到登录页！");
    }

    /**
     * 用户第一次社交登录时，会引导用户进行用户注册或绑定，此服务用于在注册或绑定页面获取社交网站用户信息
     *
     * @param request 请求
     * @return SocialUserInfo 实体类
     */
    @GetMapping(SecurityConstants.DEFAULT_SOCIAL_USER_INFO_URL)
    public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        return buildSocialUserInfo(connection);
    }

    @GetMapping("/session/invalid")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public JsonData sessionInvalid() {
        String message = "session失效";
        return JsonData.fail(message);
    }

}
